<script lang="ts">
	import { onMount } from 'svelte'
	import type { PageData } from './$types'
	import { goto } from '$app/navigation'
	import { Pane, Splitpanes } from 'svelte-splitpanes'
	import * as commands from '$lib/commands'
	import { codemirror, withCodemirrorInstance } from '@neocodemirror/svelte'
	import { javascript } from '@codemirror/lang-javascript'
	import {
		Tabs,
		TabItem,
		Table,
		TableBody,
		TableBodyCell,
		TableBodyRow,
		TableHead,
		TableHeadCell,
		Checkbox,
	} from 'flowbite-svelte'
	import {
		UserCircleSolid,
		GridSolid,
		AdjustmentsVerticalSolid,
		ClipboardSolid,
	} from 'flowbite-svelte-icons'
	import { format_datetime } from '$lib'
	import TBotChart from '$lib/TBotChart.svelte'
	import { readonly } from 'svelte/store'
	import StrategyEditor from '$lib/StrategyEditor.svelte'
	import type { GetParams } from '$lib/bindings'

	export let data: PageData

	let tbot_is_running = false

	// This acts a readonly store. $ notation works here
	const cmInstance = withCodemirrorInstance()
	let tbotChart: TBotChart

	let hoveredRowIndex: number | null = null

	function handleRowHover(index: number) {
		hoveredRowIndex = index
	}

	function handleRowUnhover() {
		hoveredRowIndex = null
	}

	let currentPage = 1
	let hasMoreData = true
	let tbots: any[] = [] // Initially empty, will be filled with server data

	async function fetchData(page: number) {
		console.log(`fetchData page=${page}`)
		// Fetch data from the server for the given page
		const response = await fetch(`https://your-api.com/tbots?page=${page}`)
		const data = await response.json()

		// Update state
		tbots = [...tbots, ...data.tbots]
		hasMoreData = data.hasMore
	}

	let isFetching = false

	function handleScroll(event: Event) {
		if (
			isFetching ||
			!hasMoreData ||
			window.innerHeight + document.documentElement.scrollTop !==
				document.documentElement.offsetHeight
		) {
			return
		}

		isFetching = true
		fetchData(currentPage + 1).then(() => {
			isFetching = false
			currentPage++
		})
	}

	onMount(() => {
		// window.addEventListener('scroll', handleScroll)
		// return () => window.removeEventListener('scroll', handleScroll)

		console.log('(bots/[id]/page.svelte) onMount() data=', data)
	})

	async function start_trade_bot_backtest(
		event: MouseEvent & { currentTarget: EventTarget & HTMLButtonElement },
	) {
		tbot_is_running = true
		// Define the argument
		const args: GetParams = {
			id: data.id, // "j9tpv2dyh3op2jwgr107",
		}
		try {
			const res = await commands.start_trade_bot_backtest(args)

			console.log('(tbots/[id]/+page.ts) start_trade_bot_backtest res=', res, ' args=', args)

			if (res.error) {
				// If the response status is not OK, throw an error
				throw new Error(
					`(tbots/[id]/+page.ts) start_trade_bot_backtest Server returned an error: ${res.error}`,
				)
			}
		} catch (error) {
			// If there's any error (e.g., network issue), return sample data
			console.error('(tbots/[id]/+page.ts) start_trade_bot_backtest Error running tbot: ', error)
		}
	}
</script>

<div class="bg-gray-200 w-full h-svh">
	<div class="w-full h-9/10 grid grid-cols-5">
		<div class="h-full col-span-4 bg-blue-500">
			{#if data.klineFlats && data.trade_bot}
				<TBotChart
					bind:this={tbotChart}
					klines={data.klineFlats}
					trade_bot={data.trade_bot}
					trade_orders={data.trade_orders}
				/>
			{/if}
		</div>
		<div class="h-full col-span-1 bg-green-500 overflow-auto">
			<Splitpanes style="height: 100%" pushOtherPanes={false} horizontal>
				<Pane size={60}>
					<div class="bg-orange-400 flex">
						<div class="grow py-1 px-2">TradeOrders</div>
						<div class="flex-none">
							<button
								class="bg-blue-500 text-white mx-2 px-8 py-1"
								on:click={start_trade_bot_backtest}
								disabled={tbot_is_running}
							>
								Back Test
							</button>
						</div>
					</div>
					<div class="overflow-auto w-full h-full flex flex-col">
						<Table hoverable={true}>
							<TableHead defaultRow={false}>
								<tr
									class="bg-gray-400 text-center text-xs font-medium text-gray-900 uppercase sticky top-0 z-10"
								>
									<TableHeadCell padding="pr-2" class="text-nowrap sticky left-0 top-0 bg-gray-400">
										指令类型
									</TableHeadCell>
									<TableHeadCell padding="pr-2" class="text-nowrap">指令数量</TableHeadCell>
									<TableHeadCell padding="pr-2" class="text-nowrap">指令价格</TableHeadCell>
									<TableHeadCell padding="pr-2" class="text-nowrap">指令时间</TableHeadCell>
								</tr>
							</TableHead>
							<TableBody
								tableBodyClass="divide divide-solid divide-green-200 text-xs text-gray-500"
							>
								{#each data.trade_orders as trade_order, index (trade_order.id?.id.String)}
									<TableBodyRow
										class="divide-x divide-slate-200 hover:bg-green-400"
										tabindex={index}
										id={index}
									>
										<TableBodyCell
											tdClass="pr-1"
											class="text-xs font-medium text-gray-900 whitespace-nowrap sticky left-0 bg-gray-200"
										>
											{trade_order.order_type}
										</TableBodyCell>
										<TableBodyCell tdClass="pr-1">{trade_order.order_amount}</TableBodyCell>
										<TableBodyCell tdClass="pr-1">{trade_order.order_price}</TableBodyCell>
										<TableBodyCell tdClass="pr-1">
											{#if trade_order.klts && trade_order.klt}
												{format_datetime('', trade_order.klts, trade_order.klt)}
											{/if}
										</TableBodyCell>
									</TableBodyRow>
								{/each}
								<TableBodyRow><TableBodyCell colspan="4">Bottom Line</TableBodyCell></TableBodyRow>
							</TableBody>
						</Table>
					</div>
				</Pane>
				<Pane size={20}>
					<div class="bg-blue-400 px-2">Used Indicators(Up to 4)</div>
					<div class="w-full h-full min-h-96 overflow-auto">
						<Table hoverable={true}>
							<TableHead defaultRow={false}>
								<tr
									class="bg-gray-400 text-left text-xs font-medium text-gray-900 uppercase sticky top-0 z-10"
								>
									<TableHeadCell padding="pr-2" class="text-nowrap">使用</TableHeadCell>
									<TableHeadCell padding="pr-2" class="text-nowrap">指标</TableHeadCell>
								</tr>
							</TableHead>
							<TableBody
								tableBodyClass="divide divide-solid divide-green-200 text-xs text-gray-500"
							>
								{#if data.trade_bot && data.trade_bot.indicators}
									{#each data.trade_bot.indicators as tsi, index (tsi.gk)}
										<TableBodyRow
											class="divide-x divide-slate-200 hover:bg-green-400"
											tabindex={index}
										>
											<TableBodyCell tdClass="pr-1 w-12">
												<Checkbox bind:checked={tsi.is_used} disabled></Checkbox>
											</TableBodyCell>
											<TableBodyCell tdClass="pr-1">{tsi.gk}</TableBodyCell>
										</TableBodyRow>
									{/each}
								{/if}
								<TableBodyRow>
									<TableBodyCell colspan="2">Bottom Line</TableBodyCell>
								</TableBodyRow>
							</TableBody>
						</Table>
					</div>
				</Pane>
				<Pane size={20}>
					<div class="bg-blue-400 px-2">Used MaLines(Up to 9)</div>
					<div class="w-full h-full min-h-96 overflow-auto">
						<Table hoverable={true}>
							<TableHead defaultRow={false}>
								<tr
									class="bg-gray-400 text-left text-xs font-medium text-gray-900 uppercase sticky top-0 z-10"
								>
									<TableHeadCell padding="pr-2" class="text-nowrap">使用</TableHeadCell>
									<TableHeadCell padding="pr-2" class="text-nowrap">均线名称</TableHeadCell>
									<TableHeadCell padding="pr-2" class="text-nowrap">均线周期</TableHeadCell>
								</tr>
							</TableHead>
							<TableBody
								tableBodyClass="divide divide-solid divide-green-200 text-xs text-gray-500"
							>
								{#if data.trade_bot && data.trade_bot.malines}
									{#each data.trade_bot.malines as tsml, index (tsml.gk + '_' + tsml.period)}
										<TableBodyRow
											class="divide-x divide-slate-200 hover:bg-green-400"
											tabindex={index}
										>
											<TableBodyCell tdClass="pr-1 w-12">
												<Checkbox bind:checked={tsml.is_used} disabled></Checkbox>
											</TableBodyCell>
											<TableBodyCell tdClass="pr-1">{tsml.gk}</TableBodyCell>
											<TableBodyCell tdClass="pr-1">{tsml.period}</TableBodyCell>
										</TableBodyRow>
									{/each}
								{/if}
								<TableBodyRow>
									<TableBodyCell colspan="3">Bottom Line</TableBodyCell>
								</TableBodyRow>
							</TableBody>
						</Table>
					</div>
				</Pane>
			</Splitpanes>
		</div>
	</div>
	<div class="w-full pt-1 overflow-auto flex flex-col relative h-lvh">
		<Tabs
			tabStyle="full"
			class="flex "
			activeClasses="px-1 pt-1 pb-2 text-primary-600 bg-gray-100  dark:bg-gray-800 dark:text-primary-500"
			inactiveClasses="px-1 pt-1 pb-2 text-gray-500  hover:text-gray-600 hover:bg-gray-50 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-300"
			contentClass="p-0 bg-gray-50  dark:bg-gray-800"
		>
			<TabItem open>
				<div slot="title" class="flex items-center gap-2">
					<GridSolid size="sm" />
					策略{data.trade_bot?.strategy_name}
				</div>
				<div class="w-full h-full min-h-96 bg-white text-black">
					{#if data.tradeStrategy}
						<StrategyEditor tradeStrategy={data.tradeStrategy}></StrategyEditor>
					{/if}
				</div>
			</TabItem>

			<TabItem>
				<div slot="title" class="flex items-center gap-2">
					<GridSolid size="sm" />
					{data.trade_bot?.security_name}({data.trade_bot?.security_id?.id.String})
				</div>
				<div class="text-sm text-gray-500 dark:text-gray-400 flex flex-col">
					<div class="flex-none">立讯转债，回测盈亏比(20.6%):</div>
					<div class="grow">
						{#each Array.from({ length: 30 }, (_, i) => i) as number}
							Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor
							incididunt ut labore et dolore magna aliqua. {number}<br />
						{/each}
					</div>
				</div>
			</TabItem>
			<TabItem>
				<div slot="title" class="flex items-center gap-2">
					<GridSolid size="sm" />
					贵州茅台
				</div>
				<p class="text-sm text-gray-500 dark:text-gray-400">
					<b>Open Funds TBots:</b>
					{#each Array.from({ length: 30 }, (_, i) => i) as number}
						Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor
						incididunt ut labore et dolore magna aliqua. {number}<br />
					{/each}
				</p>
			</TabItem>
			<TabItem>
				<div slot="title" class="flex items-center gap-2">
					<GridSolid size="sm" />
					中国银行
				</div>
				<p class="text-sm text-gray-500 dark:text-gray-400">
					<b>Convertible Bonds TBots:</b>
					{#each Array.from({ length: 30 }, (_, i) => i) as number}
						Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor
						incididunt ut labore et dolore magna aliqua. {number}<br />
					{/each}
				</p>
			</TabItem>
		</Tabs>
	</div>
</div>
